package cn.com.callback

import cn.com.kh.KHUtil
import com.elite.groovy.kh.HttpClientUtil
import com.elite.groovy.util.EliteBean
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.SimpleDateFormat

/**
 *
 * @Title: aipHSTRecycle_operation_timing
 * @Description:节假日查询
 * @author: liao
 *
 */

public class apiSyncHolidays implements ServiceBackInvoke {

    private static final Log log = LogFactory.getLog(apiSyncHolidays.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        log.debug("-----------------节假日查询接口-----------------");

        try {

            JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
            SyncHolidays(jt, null);

        } catch (Exception e) {
            log.error("节假日查询-接口处理异常" + e.getMessage());
        }
    }


    // 自动同步节假日
    public static void SyncHolidays(JdbcTemplate jt, JSONObject callJson) {
        try {
            String apiUrl = "http://apis.juhe.cn/fapig/calendar/day?key=4d959f7c30ff85fdc2ce9be4ee1d8d74&detail=1";

            String[] workTimeInfo = "09:00:00|17:30:00|12:00:00|13:00:00".split("\\|");
            String Work_Starttime = workTimeInfo[0];
            String Work_Endtime = workTimeInfo[1];
            String Noon_Starttime = workTimeInfo[2];
            String Noon_Endtime = workTimeInfo[3];
            log.debug("状态描述Work_Starttime：" + Work_Starttime + " Work_Endtime：" + Work_Endtime + " Noon_Starttime：" + Noon_Starttime + " Noon_Endtime：" + Noon_Endtime);

            //当前sysc_datetype表里面有哪些节日
            String dateType_SQL = "Select Datetypeid, Datetypedesc From Sysc_Datetype";
            List<Map<String, Object>> dateType_List = jt.queryForList(dateType_SQL);

            String StartTime = "";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar startDate = Calendar.getInstance();

            int loopLimit = 0;
            while (loopLimit < 2) {
                StartTime = sdf.format(startDate.getTime());
                String wxTokenURL = apiUrl + "&date=" + URLEncoder.encode(StartTime);//地址拼接，用于对字符串进行URL编码处理
                log.debug("完整的URL地址：" + wxTokenURL);

                String wxTokenResult = HttpClientUtil.get(wxTokenURL);
                log.debug("响应信息：" + wxTokenResult);
                JSONObject wxTokenJson = JSONObject.fromObject(wxTokenResult);
                log.debug("Json内容：" + wxTokenJson);

                // 生成下一个日期
                startDate.add(Calendar.DATE, 1);
                loopLimit++;

                if (wxTokenJson.getString("error_code").equals("0")) {//获取到正常日期
                    JSONObject resultJson = wxTokenJson.getJSONObject("result");//获取主要对象信息
                    String free_Type = resultJson.getString("statusDesc");//状态描述，节假日/工作日/周末
                    String date = resultJson.getString("date");  //日期
                    String week = resultJson.getString("week");  //星期几
                    String term = resultJson.getString("term");  //节日描述，如端午节...
                    log.debug("状态描述：" + free_Type + " 日期：" + date + " 星期几：" + week + " 节日：" + term);

                    // 识别dateType
                    String dateType = "000009";

                    if (free_Type.equals("节假日") || free_Type.equals("周末")) {
                        if (!KHUtil.isNull(term)) {//如果节日不为空,进行匹配节日ID，否则只更新时间和星期
                            for (int i = 0; i < dateType_List.size(); i++) {//遍历节日类型，如果匹配到对应的节日类型，则插入
                                String Datetypedesc = dateType_List.get(i).get("Datetypedesc").toString();//节日描述
                                if (Datetypedesc.equals(term)) {
                                    dateType = dateType_List.get(i).get("Datetypeid").toString();
                                    break;
                                }
                            }
                        }

                    } else if (free_Type.equals("工作日")) {//否则就是工作日
                        dateType = "000010";//工作日
                    } else {
                        dateType = "000009";//周末
                    }

                    // 处理表中数据
                    String check_SQL = "Select Freedate, Datetype, Updateby From c_Freedate Where Date_Format(Freedate, '%Y-%m-%d') = '" + StartTime + "'";
                    List<Map<String, Object>> check_List = jt.queryForList(check_SQL);
                    log.debug("同步节假日完成 处理表中数据：" + check_List.toString());

                    if (check_List.size() > 0) {
                        if (check_List.get(0).get("Updateby").toString().equals("######")) {//如果查到数据 并且创建人为系统，则修改
                            if (dateType.equals("000010")) {
                                jt.update("Update c_Freedate Set Datetype = '" + dateType + "', Work_Starttime = '" + Work_Starttime + "', Work_Endtime = '" + Work_Endtime + "', Noon_Starttime = '" + Noon_Starttime + "', Noon_Endtime = '" + Noon_Endtime + "', Updateby = '######' Where Date_Format(Freedate, '%Y-%m-%d') = '" + StartTime + "'");
                            } else {
                                jt.update("Update c_Freedate Set Datetype = '" + dateType + "', Work_Starttime = '', Work_Endtime = '', Noon_Starttime = '', Noon_Endtime = '', Updateby = '######' Where Date_Format(Freedate, '%Y-%m-%d') = '" + StartTime + "'");

                            }
                        } else {
                            log.warn("日期" + StartTime + " 疑似被人工介入修改,忽略处理");
                        }

                    } else {//如果没有查到，则插入
                        if (dateType.equals("000010")) {
                            jt.update("Insert Into c_Freedate (Freedate, Datetype, Work_Starttime, Work_Endtime, Noon_Starttime, Noon_Endtime, Updateby) Values ('" + StartTime + "', '" + dateType + "', '" + Work_Starttime + "', '" + Work_Endtime + "', '" + Noon_Starttime + "', '" + Noon_Endtime + "', '######')");
                        } else {
                            jt.update("Insert Into c_Freedate (Freedate, Datetype, Work_Starttime, Work_Endtime, Noon_Starttime, Noon_Endtime, Updateby) Values ('" + StartTime + "', '" + dateType + "', '', '', '', '', '######')");

                        }
                    }
                } else if (wxTokenJson.getString("error_code").equals("10012")) {
                    log.warn("接口返回10012超出请求次数:" + wxTokenJson.getString("reason"));
                    break;
                }
            }

            log.debug("同步节假日完成 总调用次数：" + loopLimit);

        } catch (Exception e) {
            log.error("节假日查询-接口处理异常", e);
        }
    }
}